<template>
  <!-- 可移动容器 -->
  <div class="draggable-box" ref="draggableBoxRef">
    <!-- 用于移动的弹窗头部 -->
    <div class="slot-header" @mousedown="($event) => startDrag($event)">
      <slot name="header"></slot>
    </div>
    <!-- 弹窗体 -->
    <div class="slot-body">
      <slot name="body"></slot>
    </div>
  </div>
</template>

<script lang="ts">
export default {
  name: 'MoveByHeaderBox'
}
</script>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'

const draggableBoxRef = ref<HTMLElement | null>(null)
let isDragging = ref(false)
let mouseOffsetX = 0
let mouseOffsetY = 0

const startDrag = (event: MouseEvent) => {
  const target = (event.target as HTMLElement).parentElement as HTMLElement
  if (target.classList.contains('draggable-box')) {
    isDragging.value = true
    mouseOffsetX = event.clientX - target.offsetLeft
    mouseOffsetY = event.clientY - target.offsetTop
    document.addEventListener('mousemove', handleDrag)
    document.addEventListener('mouseup', stopDrag)
  }
}

const handleDrag = (event: MouseEvent) => {
  if (isDragging.value && draggableBoxRef.value) {
    const newLeft = event.clientX - mouseOffsetX
    const newTop = event.clientY - mouseOffsetY
    draggableBoxRef.value.style.left = `${newLeft}px`
    draggableBoxRef.value.style.top = `${newTop}px`
  }
}

const stopDrag = () => {
  isDragging.value = false
  document.removeEventListener('mousemove', handleDrag)
  document.removeEventListener('mouseup', stopDrag)
}

onMounted(() => {
  if (draggableBoxRef.value) {
    draggableBoxRef.value.style.position = 'absolute'
  }
})

onUnmounted(() => {
  document.removeEventListener('mousemove', handleDrag)
  document.removeEventListener('mouseup', stopDrag)
})
</script>

<style lang="scss" scoped>
.draggable-box {
  position: relative;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  box-shadow: 1px 1px rgb(185, 185, 185), -0.1px 0 0.1em rgb(145, 145, 145);

  .slot-header {
    cursor: move;
    pointer-events: auto;
    width: 100%;
    height: 26px;
  }

  .slot-body {
    width: 100%;
    height: 0;
    flex: 1;
  }
}
</style>
